Reverse vowels of a string¶
Time: O(N); Space: O(1); easy
Write a function that takes a string as input and reverse only the vowels of a string.
Example 1:
Input: s = “hello”
Output: “holle”
Example 2:
Input: s = “leetcode”
Output: “leotcede”
Note:
The vowels does not include the letter “y”.
[1]:
class Solution1(object):
"""
Time: O(N)
Space: O(1)
"""
def reverseVowels(self, s):
"""
:type s: str
:rtype: str
"""
vowels = "aeiou"
string = list(s)
i, j = 0, len(s) - 1
while i < j:
if string[i].lower() not in vowels:
i += 1
elif string[j].lower() not in vowels:
j -= 1
else:
string[i], string[j] = string[j], string[i]
i += 1
j -= 1
return ''.join(string)
[3]:
sol = Solution1()
s = "hello"
assert sol.reverseVowels(s) == "holle"
s = "leetcode"
assert sol.reverseVowels(s) == "leotcede"